package com.sgb.kjwl.view.ui.activity.manage.special;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityInviteMemberListBinding;
import com.sgb.kjwl.databinding.ItemInviteMemberListBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.manage.special.CompanyEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.event.special.InviteEvent;
import com.sgb.kjwl.viewmodel.manage.CompanySpecialViewModel;
import com.sgb.member.MemberConfig;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.MToast;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 邀请列表页
 */
@Route(path = AppRouteConstant.InviteMemberListActivity)
public class InviteMemberListActivity extends AppActivity {

    @Inject
    public CompanySpecialViewModel mViewModel;

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;


    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity<Object>>>>>> addressEntityList = new ArrayList<>();
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity<Object>>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity<Object>>>> opt3;
    //城市列表
//    private List<AddressEntity<List<AddressEntity>>> cityList;
    //区域列表
    private List<List<AddressEntity<Object>>> areaList;

    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private boolean isLoaded = false;
    private String mAreaCode;

    private boolean isNewAddress;

    private CityPickView cityOption;

    private ActivityInviteMemberListBinding mBinding;

    boolean isLoadMore = false; // 是否是加载更多
    private boolean isEnableLoadMore = false; //是否可以上拉加载

    private InviteMemberAdapter mAdapter;

    private CompanyEntity mInviteCompanyEntity;//当前选的

    private String mProvinceNo = "";
    private String mCityNo = "";
    private String mAreaNo = "";
    private String mCompanyName = "";

    public static void launch(Context context){
        Intent intent = new Intent(context, InviteMemberListActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerSelfComponent.builder().appComponent(appComponent)
                .selfModule(new SelfModule()).build().inject(this);
    }


    @Override
    protected void initView() {
        super.initView();
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_invite_member_list);
        mBinding.include.ivBack.setOnClickListener(v -> finish());
        mBinding.include.titleView.setText("邀请成员");
        mBinding.tvFilter.setOnClickListener(v -> {
            if (!addressEntityList.isEmpty()) {
                showCityPop();
            } else {
                mViewModel.getAddressModel(this);
            }
            mBinding.tvInvite.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.icon_up_grey), null);
        });
        mBinding.tvSearchDelete.setOnClickListener(view -> {
            mBinding.etView.setText("");
        });
        mBinding.tvInvite.setOnClickListener(v -> {
            if (mInviteCompanyEntity == null){
                MToast.showToast(this, "请选择邀请的企业");
                return;
            }
            InviteMemberPostActivity.Companion.launch(this, mInviteCompanyEntity, true);
        });
        initLiveDate();
        initRecycleView();
        mBinding.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
               mBinding.tvSearchDelete.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
               mCompanyName = s.toString();
            }
        });
        mBinding.etView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    isLoadMore = false;
                    getData();
                    closeKeybord();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void init() {
        super.init();
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        isLoadMore = false;
        getData();
    }

    private void initRecycleView() {
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                getData();
                mBinding.refreshLayout.finishLoadMore(500);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = false;
                getData();
                mBinding.refreshLayout.finishRefresh(500);
            }
        });
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(new ScrollBoundaryDecider() {
            @Override
            public boolean canRefresh(View content) {
                if (mBinding.recycleView == null) return false;
                if (mBinding.recycleView.computeVerticalScrollOffset() == 0)
                    return true;
                return false;
            }

            @Override
            public boolean canLoadMore(View content) {
                if (mBinding.recycleView == null) return false;
                //获取recyclerView的高度
                mBinding.recycleView.getHeight();
                //整个View控件的高度
                int scrollRange = mBinding.recycleView.computeVerticalScrollRange();
                //当前屏幕之前滑过的距离
                int scrollOffset = mBinding.recycleView.computeVerticalScrollOffset();
                //当前屏幕显示的区域高度
                int scrollExtent = mBinding.recycleView.computeVerticalScrollExtent();
                int height = mBinding.recycleView.getHeight();
                if (height > scrollRange) {
                    return false;
                }
                if (isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent) {
                    return true;
                }
                return false;
            }
        });
        // RecyclerView 和 Adapter 关联
        mAdapter = new InviteMemberAdapter(R.layout.item_invite_member_list);
        mAdapter.bindToRecyclerView(mBinding.recycleView);
        mBinding.recycleView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        View empty = LayoutInflater.from(this).inflate(R.layout.layout_empty_view, mBinding.recycleView, false);
        mAdapter.setEmptyView(empty);
        mBinding.recycleView.addItemDecoration(
                new RecyclerCustomDecoration(
                        0f,
                        0f,
                        0f,
                        getResources().getDimension(R.dimen.dp1), getResources().getColor(R.color.color_main_bg)
                )
        );
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<CompanyEntity> data = mAdapter.getData();
                if (data != null && !data.isEmpty()){
                    if (data.get(position).isChoose()) {
                        mInviteCompanyEntity = mAdapter.getData().get(position);
                        return;
                    }
                    for (int i = 0; i < data.size(); i++) {
                        if (i == position){
                            mInviteCompanyEntity = mAdapter.getData().get(i);
                            mAdapter.getData().get(i).setChoose(true);
                        } else {
                            mAdapter.getData().get(i).setChoose(false);
                        }
                    }
                };
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    private void getData() {
        mViewModel.getAllCompany(mCompanyName, mProvinceNo, mCityNo, mAreaNo, isLoadMore);
    }

    private void initLiveDate() {
        mViewModel.getMAllAddress().observe(this, new Observer<ArrayList<AddressEntity<List<AddressEntity<List<AddressEntity<Object>>>>>>>() {
            @Override
            public void onChanged(ArrayList<AddressEntity<List<AddressEntity<List<AddressEntity<Object>>>>>> addressEntities) {
                if (!addressEntities.isEmpty()){
                    initAddressData(addressEntities);
                }
            }
        });
        mViewModel.getMInviteMemberCompanyList().observe(this, new Observer<List<CompanyEntity>>() {
            @Override
            public void onChanged(List<CompanyEntity> companyEntities) {
                isEnableLoadMore = companyEntities != null && companyEntities.size() >= 10;
                if (companyEntities != null) {
                    if (isLoadMore) {
                        mAdapter.addData(companyEntities);
                    } else {
                        mAdapter.setNewData(companyEntities);
                    }
                }
            }
        });
    }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity<Object>>>>>> datas) {
        this.addressEntityList.clear();
        addressEntityList.addAll(datas);
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }


    private void initJsonData() {

        for (int i = 0; i < addressEntityList.size(); i++) {

            if (!isNewAddress) {
                if (addressEntityList.get(i).getId().equals(mProvinceNo)) {
                    cityPosition1 = i;
                }
            }

//            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {

                if (!isNewAddress) {
                    if (addressEntityList.get(i).getChildren().get(j).getId().equals(mCityNo)) {
                        cityPosition2 = j;
                    }
                }
                List<AddressEntity<Object>> cityAreaList = new ArrayList<>();
                List<AddressEntity<Object>> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                    if (!isNewAddress) {
                        for (int k = 0; k < children.size(); k++) {
                            if (children.get(k).getId().equals(mAreaNo)) {
                                cityPosition3 = k;
                            }
                        }
                    }
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };


    private void showCityPop() {
        if (cityOption == null) {
            cityOption = new CityPickBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    String areaName;
                    if (opt3.get(options1).get(options2).get(options3) == null) {
                        areaName = "";
                    } else {
                        areaName = opt3.get(options1).get(options2).get(options3).getName();
                        mAreaCode = opt3.get(options1).get(options2).get(options3).getNo();
                        cityPosition3 = options3;
                    }
                    String content = addressEntityList.get(options1).getName() + opt2.get(options1).get(options2).getName() + areaName;
                    mBinding.tvFilter.setText(areaName);
                    cityPosition1 = options1;
                    cityPosition2 = options2;
                    mProvinceNo = addressEntityList.get(options1).getNo();
                    mCityNo = opt2.get(options1).get(options2).getNo();
                    mAreaNo = opt3.get(options1).get(options2).get(options3).getNo();
                    mBinding.tvInvite.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.icon_down_grey), null);
                    getData();
                }
            }).setCancelText("取消").setSubCalSize(15)
                    .setCancelColor(getResources().getColor(R.color.color_tab_two))
                    .setSubmitText("确定")
                    .setSubmitColor(getResources().getColor(R.color.color_main)).build();
        }
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(InviteEvent event){
        if (!isFinishing()){
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    class InviteMemberAdapter extends BaseQuickAdapter<CompanyEntity, BaseViewHolder>{
        private ItemInviteMemberListBinding mItemBinding;

        private ForegroundColorSpan mColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.color_title_medium));


        private SpannableStringBuilder ssb;

        public InviteMemberAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder helper, CompanyEntity item) {
            mItemBinding = DataBindingUtil.bind(helper.itemView);
            setColorSpan(getResources().getString(R.string.com_addr, TextUtils.isEmpty(item.getBusinessAddress()) ? "" : item.getBusinessAddress()), mItemBinding.tvAddress);
            setColorSpan(getResources().getString(R.string.com_attr, TextUtils.isEmpty(item.getMainBusiness()) ? "" : item.getMainBusiness()), mItemBinding.tvMainBusiness);
            setColorSpan(getResources().getString(R.string.com_name, TextUtils.isEmpty(item.getCompanyName()) ? "" : item.getCompanyName()), mItemBinding.tvName);
            mItemBinding.ivChoose.setImageResource(!item.isChoose() ? R.drawable.icon_choose_normal : R.drawable.icon_choose_select);
        }

        private void setColorSpan(String content, TextView tv) {
            ssb = new SpannableStringBuilder(content);
            ssb.setSpan(mColorSpan, content.indexOf("："), content.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            tv.setText(ssb);
        }
    }
}
